package com.franklin.maven.localcleaner.api.swing.text;

import com.intellij.ui.components.JBLabel;

import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Comparator;
import java.util.List;


/**
 * 文本高亮TextArea
 * @author Franklin
 * @since 2022/04/05 22:41
 */
public class HighlightTextTextArea extends JTextArea {

    private final Color highlightColor;
    private final List<String> highlightTextList;
    private final String text;

    public HighlightTextTextArea(
            Icon icon,
            Color highlightColor,
            List<String> highlightTextList,
            String text
    ) {
        JBLabel label = new JBLabel(icon);
        label.setSize(20,20);
        this.add(label,0);
        this.highlightColor = highlightColor;
        this.highlightTextList = highlightTextList;
        this.text = "    " + text;

        this.init();
    }

    private void init(){
        this.setText(text);
        this.setEditable(false);
        DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(highlightColor);
        Highlighter highlighter = this.getHighlighter();
        this.highlightTextList.sort(Comparator.comparingInt(text -> -text.length()));
        for (String highlightText : this.highlightTextList) {
            int position = 0;
            while ((position = this.text.indexOf(highlightText,position)) >= 0){
                try {
                    highlighter.addHighlight(position,position + highlightText.length(),highlightPainter);
                    position += highlightText.length();
                } catch (BadLocationException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
